package com.mbbb.yygh.hosp.receiver;

import com.mbbb.yygh.hosp.service.ScheduleService;
import com.mbbb.yygh.model.hosp.Schedule;
import com.mbbb.yygh.rabbit.RabbitService;
import com.mbbb.yygh.rabbit.constant.MqConst;
import com.mbbb.yygh.vo.msm.MsmVo;
import com.mbbb.yygh.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class HospitalReceiver {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),
                    exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
                    key = {MqConst.ROUTING_ORDER}
    ))
    public void receiver(OrderMqVo orderMqVo, Message message, Channel channel) throws IOException {

        //判断：①取消预约 +1    ②更新排班
        if (orderMqVo.getReservedNumber() != null) { //更新排班
            //1.根据mq发送的消息中的参数，更新排班数据
            //根据排班id查询排班数据
            Schedule schedule = scheduleService.getScheduleById(orderMqVo.getScheduleId());
            //设置更新数据
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            //调用方法更新
            scheduleService.updateSchedule(schedule);
        } else { //取消预约 +1
            //1.根据mq发送的消息中的参数，更新排班数据
            //根据排班id查询排班数据
            Schedule schedule = scheduleService.getScheduleById(orderMqVo.getScheduleId());
            //设置更新数据 +1
            int availableNumber = schedule.getAvailableNumber().intValue() + 1;
            schedule.setAvailableNumber(availableNumber);
            scheduleService.updateSchedule(schedule);
            //调用方法更新
            scheduleService.updateSchedule(schedule);
        }

        //2.给service_msm模块发消息，让它发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if (msmVo != null) {
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }
    }
}
